<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Example</title>
</head>
<body>
    <h1>WebSocket Chat</h1>
    <textarea id="messages" rows="10" cols="30" readonly></textarea><br>
    <input type="text" id="messageInput" placeholder="Type a message...">
    <button id="sendButton">Send</button>

    <script>
        // 创建 WebSocket 连接
        const socket = new WebSocket('ws://iot.daguiot.com:42048'); // 替换为你的服务器地址

        // 当连接成功时
        socket.onopen = function() {
            console.log('WebSocket connection established');
            document.getElementById('messages').value += 'Connected to server\n';
        };

        // 当接收到消息时
        socket.onmessage = function(event) {
            console.log('Message from server: ', event.data);
            document.getElementById('messages').value += 'Server: ' + event.data + '\n';
        };

        // 当连接关闭时
        socket.onclose = function() {
            console.log('WebSocket connection closed');
            document.getElementById('messages').value += 'Disconnected from server\n';
        };

        // 发送消息
        document.getElementById('sendButton').onclick = function() {
            const message = document.getElementById('messageInput').value;
            socket.send(message);
            document.getElementById('messages').value += 'You: ' + message + '\n';
            document.getElementById('messageInput').value = ''; // 清空输入框
        };
    </script>
</body>
</html>